package edu.cornell.cubooks.domain;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;

/**
 * Business object which represents user.
 * 
 * @author CUBooks Team
 *
 */
@Entity
@Table(name="user",
    uniqueConstraints = {@UniqueConstraint(columnNames={"username"})}
)
public class User implements Serializable, UserDetails {
		
	private static final long serialVersionUID = 3517156244746972270L;
	
    @Id 
    @GeneratedValue
	private Integer id;
    
	@Column(name="first_name")
	private String firstName;
	
	@Column(name="last_name")
	private String lastName;
	
	@Column(name="email_address")
	private String emailAddress;

	@Transient
	private String cemailAddress;
	
	@Transient
	private String captcha;
	
	private String username;
	
	private String token;
	
	private Integer age;
	
	@Column(name="password")
	private String password;
	@Transient
	private String cpassword;
	
	private boolean enabled = true;
	private boolean credentialsNonExpired = true;
	private boolean accountNonLocked = true;
	private boolean accountNonExpired = true;
	
	@Column(name="last_login_at")
	private Date lastLoginAt;
	
	@Column(name="current_login_at")
	private Date currentLoginAt;
	
	@Column(name="request_seller")
	private Integer requestSeller;

	@Column(name = "login_attempts", nullable = false)
	private Integer loginAttempts = 0;
	
	// many users have many roles
	// fetch eager always loads roles when loading user's data
	@ManyToMany(fetch=FetchType.EAGER)
	@JoinTable(name = "user_role",    
		joinColumns = { @JoinColumn(name = "user_id")},  
		inverseJoinColumns={@JoinColumn(name="role_id")})  
	private Set<Role> roles = new HashSet<Role>();
	
	// one user has many postings
	@OneToMany(mappedBy="user", fetch=FetchType.LAZY)
    public Set<Posting> postings;
	
    // one seller  has many feedback
	@OneToMany(mappedBy="user", fetch=FetchType.LAZY)
    public Collection<Feedback> feedbacks;
	
	public User() {
		// set default role to buyer.
		Role role = new Role(Role.ROLE_BUYER);
		role.setName(Role.ROLE_BUYER_NAME);
		this.getRoles().add(role);
	}
	
	public Integer getId() {
		return id;
	}
	
    public void setId(Integer id) {
		this.id = id;
	}
    
	public String getFirstName() {
		return firstName;
	}
	
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	
	public String getLastName() {
		return lastName;
	}
	
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public String getEmailAddress() {
		return emailAddress;
	}
	
	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}
	
	public Integer getAge() {
		return age;
	}
	
	public void setAge(Integer age) {
		this.age = age;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCemailAddress() {
		return cemailAddress;
	}

	public void setCemailAddress(String cemailAddress) {
		this.cemailAddress = cemailAddress;
	}

	public String getCpassword() {
		return cpassword;
	}

	public void setCpassword(String cpassword) {
		this.cpassword = cpassword;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public Set<Posting> getPostings() {
		return postings;
	}

	public void setBooks(Set<Posting> postings) {
		this.postings = postings;
	}

	public boolean isCredentialsNonExpired() {
		return credentialsNonExpired;
	}

	public void setCredentialsNonExpired(boolean credentialsNonExpired) {
		this.credentialsNonExpired = credentialsNonExpired;
	}

	public boolean isAccountNonLocked() {
		return accountNonLocked;
	}

	public void setAccountNonLocked(boolean accountNonLocked) {
		this.accountNonLocked = accountNonLocked;
	}

	public boolean isAccountNonExpired() {
		return accountNonExpired;
	}

	public void setAccountNonExpired(boolean accountNonExpired) {
		this.accountNonExpired = accountNonExpired;
	}
	

	public Collection<Feedback> getFeedbacks() {
		return feedbacks;
	}

	public void setFeedbacks(Collection<Feedback> feedbacks) {
		this.feedbacks = feedbacks;
	}
	
	public void setPostings(Set<Posting> postings) {
		this.postings = postings;
	}

	public Date getLastLoginAt() {
		return lastLoginAt;
	}

	public void setLastLoginAt(Date lastLoginAt) {
		this.lastLoginAt = lastLoginAt;
	}
	
	public Date getCurrentLoginAt() {
		return currentLoginAt;
	}

	public void setCurrentLoginAt(Date currentLoginAt) {
		this.currentLoginAt = currentLoginAt;
	}
		
	public String getCaptcha() {
		return captcha;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.springframework.security.userdetails.UserDetails#getAuthorities()
	 */
	public GrantedAuthority[] getAuthorities() {
		// since we are using Hibernate to take care of the relations
		// and user holds set of Roles in Set<Role> we need to 'cast' them to GrantedAuthority[]
		// to support Spring Security
		GrantedAuthority[] authorities  = null;
		if (getRoles().size() > 0) {
			for (Role role : roles) {
				GrantedAuthority authority = new GrantedAuthorityImpl(role.getName());
				authorities = (GrantedAuthority[]) ArrayUtils.add(authorities, authority);
			}
		}
		return authorities;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public Integer getRequestSeller() {
		return requestSeller;
	}

	public void setRequestSeller(Integer requestSeller) {
		this.requestSeller = requestSeller;
	}

	public Integer getLoginAttempts() {
		return loginAttempts;
	}

	public void setLoginAttempts(Integer loginAttempts) {
		this.loginAttempts = loginAttempts;
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	@Override
	public boolean equals(Object object) {
		if (object == null || !(object instanceof User)) {
			return false;
		}
		User user = (User) object;
		if (user.getId() == null || this.getId() == null) {
			return false;
		}
		if(this.getId().equals(user.getId())) {
			return true;
		}
		return false;
	}
	
	@Override
	public int hashCode() { 
		int hash = 1;
		hash = hash * 31 + id.hashCode();
		hash = hash * 31 + (username == null ? 0 : username.hashCode());
		return hash;
	}

}
